package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.io.File;
/**
 * 
 * @author msjykf
 * 将每晚待执行批次依次取出来推送到安正数据中心跑出数据
 * {"batch_id":"","template_id":"","requesttype": 1}
 * batch_id:批次号;template_id:模板ID;requesttype:请求类型 1定时任务调度 2动态页面调度
 * 
 */
public class BillBatchRequest implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(BillBatchRequest.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request,HttpServletResponse response){
		try {
			def jsonbody = Util.getRequestBody(request,'utf-8'); //获取报文
			log.debug("jsonbody:"+jsonbody);
			if(jsonbody.equals("")) {
				return "{\"msg\": \"未获取到入参报文！\",\"code\": -2}"
			}
			JSONObject obj = JSONObject.fromObject(jsonbody);
			def template_id = Util.filterForObject(obj.get("template_id"));
			if(template_id.equals("")){
				return "{\"msg\": \"template_id参数不能为空！\",\"code\": -2}"
			}
			def requesttype = Util.filterForObject(obj.get("requesttype"));
			log.debug("requesttype:"+requesttype);
			if(requesttype.equals("")) {
				return "{\"msg\": \"requesttype参数不能为空！\",\"code\": -2}"
			}
			def batch_id = ""; 	//批次
			def filepath = "";	//邮件模板存放相对路径
			def filename = ""; //邮件模板存储文件名称
			def i = 0;
			def smap = eliteBean.chaxun_sql("select dt.documentpath,dt.filename from doctemplate dt where dt.doctemplate_id='"+template_id+"'","dataSource");
			if(smap.size()==0) {
				return "{\"msg\": \"无效的模板！\",\"code\": -2}"
			}else {
				filepath = Util.filterForObject(smap[0].get("documentpath"));
				filename = Util.filterForObject(smap[0].get("filename"));
			};
			if(filepath.equals("")||filename.equals("")){
				return "{\"msg\": \"模板信息不能为空！\",\"code\": -2}"
			};
			if(requesttype.equals("1")) {
				batch_id = Util.filterForObject(obj.get("batch_id"));
				if(batch_id.equals("")){
				return "{\"msg\": \"批次号不能为空！\",\"code\": -2}"
				}
			}else if(requesttype.equals("2")) {
				smap = eliteBean.chaxun_sql("select customgetid('ST') as batch_id from dual","dataSource");
				batch_id = smap[0].get("batch_id");
				eliteBean.update("insert into statement_batch(batch_id,template_id,acceptstate)values('"+batch_id+"','"+template_id+"',0)","dataSource");
			};
			def charset = "utf-8"; //字符集
			def timeout = 100000; //请求超时时间
			def currentdate = Util.getNowString("yyyyMMdd");
			PropertiesUtil properties = new PropertiesUtil();
			def ibqurl = properties.readValue("ibqurl"); //获取webservice接口地址
			def appid = properties.readValue("appid"); //获取appId
			def ccserverip = properties.readValue("ccserverip"); //获取CallCenter访问地址
			def serverpath = properties.readValue("serverpath"); //获取EliteGeneralHttpTask服务路径
			def fileStore = properties.readValue("fileStore"); //文件存储根目录
			def billmouldid = properties.readValue("billmouldid"); //季度对账单模板ID
			def relativepath = "/statements/JJJYDZD_"+currentdate+"_"+batch_id+".txt";//文件存储相对路径
			File file = new File(fileStore+relativepath); //文件存储绝对路径
			//文件不存在，则创建文件
			if(!file.exists()) {
				file.createNewFile();
			}else {
				file.delete();
				file.createNewFile();
			}
			def httpurl = "http://"+ccserverip+"/ngs/fs/get?file="+filepath+"&d=true"; //模板下载地址
			def savefile = serverpath+filename;
			if(filepath!='') {
				Util.httpDownLoadFile(httpurl,savefile,timeout); //下载模板
			};
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			smap = eliteBean.chaxun_sql("select to_char(sk_date,'YYYY-MM-DD') as sk_date from triggermode where doctemplate_id='"+template_id+"'","dataSource");
			def sk_date = smap[0].get("sk_date");
			log.debug("sk_date:"+sk_date);
			
			int year,currentMonth;
			Calendar cal = Calendar.getInstance();
			if(sk_date.equals("")||sk_date == null){//确认时间为空取当前时间
				year = cal.get(Calendar.YEAR);// 获取年
				currentMonth = cal.get(Calendar.MONTH)+1;// 获取月，这里需要需要月份的范围为0~11，因此获取月份的时候需要+1才是当前月份值
			}else{//获取配置确认时间
				SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
				Date dt = sdft.parse(sk_date);
				cal.setTime(dt);	
				year = cal.get(Calendar.YEAR);// 获取年\
				currentMonth = cal.get(Calendar.MONTH)+1;// 获取月，这里需要需要月份的范围为0~11，因此获取月份的时候需要+1才是当前月份值
			}
			log.debug("year:"+year);
			log.debug("currentMonth:"+currentMonth);
			
			def firstDay,lastDay;
			if(currentMonth>=1 && currentMonth<=3) {
				cal.set(Calendar.YEAR, year-1);
				cal.set(Calendar.MONTH, 9);
				cal.set(Calendar.DAY_OF_MONTH,1);
				firstDay = sdf.format(cal.getTime()); //取季度第一天
				cal.set(Calendar.MONTH, 12);
				cal.set(Calendar.DAY_OF_MONTH, 0);
				lastDay = sdf.format(cal.getTime()); ////取季度最后一天
			}else if(currentMonth>=4 && currentMonth<=6) {
				cal.set(Calendar.MONTH, 0);
				cal.set(Calendar.DAY_OF_MONTH,1);
				firstDay = sdf.format(cal.getTime()); //取季度第一天
				cal.set(Calendar.MONTH, 3);
				cal.set(Calendar.DAY_OF_MONTH, 0);
				lastDay = sdf.format(cal.getTime()); ////取季度最后一天
			}else if(currentMonth>=7 && currentMonth<=9) {
				cal.set(Calendar.MONTH, 3);
				cal.set(Calendar.DAY_OF_MONTH,1);
				firstDay = sdf.format(cal.getTime()); //取季度第一天
				cal.set(Calendar.MONTH, 6);
				cal.set(Calendar.DAY_OF_MONTH, 0);
				lastDay = sdf.format(cal.getTime()); ////取季度最后一天
			}else if(currentMonth>=10 && currentMonth<=12) {
				cal.set(Calendar.MONTH, 6);
				cal.set(Calendar.DAY_OF_MONTH,1);
				firstDay = sdf.format(cal.getTime()); //取季度第一天
				cal.set(Calendar.MONTH, 9);
				cal.set(Calendar.DAY_OF_MONTH, 0);
				lastDay = sdf.format(cal.getTime()); ////取季度最后一天
			}
			log.debug("\n"+"firstDay:"+firstDay+"\n"+"lastDay:"+lastDay);
			smap = eliteBean.chaxun_sql("select min(case when date_i>"+firstDay+" then date_i else null end) as req_start,max(case when date_i<"+lastDay+" then date_i else null end) as req_end from c_calendar where workflag=1","dataSource");
			def req_start = smap[0].get("req_start");
			def req_end = smap[0].get("req_end");
			def xmlbody = "";
			if(template_id==billmouldid) {
				xmlbody = """<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
					<SOAP-ENV:Body>
						<m:executeProcedure xmlns:m="http://service.web.server.ua.businessmatrix.com/">
								<appId>"""+appid+"""</appId>
								<name>s-P_BILLSEND</name>
							<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_STARTDATE</name>
								<value>"""+firstDay+"""</value>
							</params>
							<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_ENDDATE</name>
								<value>"""+lastDay+"""</value>
							</params>
							<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_BATCHNO</name>
								<value>"""+batch_id+"""</value>
							</params>
						</m:executeProcedure>
					</SOAP-ENV:Body>
				</SOAP-ENV:Envelope>"""
			}
			if(!xmlbody.equals("")) {
				def result = Util.callWebService(ibqurl,xmlbody,charset,"",timeout);
				String[] data=new String[2];
				data[0] = "update statement_batch set requestdate=sysdate,acceptstate=0,inputmsg='"+xmlbody+"',outputmsg='"+result+"',filestore='"+relativepath+"',startdate="+firstDay+",enddate="+lastDay+",reqstartdate="+req_start+",reqenddate="+req_end+" where batch_id='"+batch_id+"'";
				data[1] = "update docproperty set no='"+batch_id+"' where doctemplate_id='"+template_id+"'";
				int[] dataresult = eliteBean.updateBatch(data,"dataSource");
				return "{\"msg\": \"请求接口成功！\",\"code\": 1}"
			}else {
				return "{\"msg\": \"未找到对应的模板！\",\"code\": -2}"
			}
		}catch(Exception e) {
			log.error("ErrorMessage： ",e);
			return "{\"msg\": \"请求接口失败！\",\"code\": -1}"
			}	
	}
}	
